package com.jie.netty.processor;

import cn.hutool.core.bean.BeanUtil;
import com.jie.constants.ChannelAttrKey;
import com.jie.constants.IMRedisKey;
import com.jie.netty.IMServerGroup;
import com.jie.netty.contant.IMConstant;
import com.jie.netty.im.UserChannelCtxMap;
import com.jie.netty.message.RunTrackMessage;
import com.jie.netty.model.IMHeartbeatInfo;
import com.jie.netty.model.IMSendInfo;
import com.jie.netty.type.IMCmdType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 类似于加入当前多人轨迹pk的通知处理器
 * @Author: 杰
 * @Project :net-disk
 * @DateTime: 2024/7/10 15:15
 **/
@Component
@Slf4j
public class RunOpenNotificationProcessor extends AbstractMessageProcessor<RunTrackMessage>{

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 加入多人轨迹pk的channel
     * @param ctx
     */
    @Override
    public synchronized void process(ChannelHandlerContext ctx, RunTrackMessage runTrackMessage) {
        //这里要将各个用户关联起来
        String roomId = runTrackMessage.getRoomId();
        String username = runTrackMessage.getUsername();
        // 绑定用户和channel
        UserChannelCtxMap.addGroupChannelCtx(roomId,ctx);
        // 设置用户id属性
        AttributeKey<String> userIdAttr = AttributeKey.valueOf(ChannelAttrKey.USER_NAME);
        ctx.channel().attr(userIdAttr).set(username);
        //设置房间号
        AttributeKey<String> roomIdAttr = AttributeKey.valueOf(ChannelAttrKey.ROOM_ID);
        ctx.channel().attr(roomIdAttr).set(roomId);
        //设置公共属性
        AttributeKey<String> publicAttr = AttributeKey.valueOf(ChannelAttrKey.PUBLIC_INFO);
        ctx.channel().attr(publicAttr).set(ChannelAttrKey.ROOM_ID);
        // 初始化心跳次数
        AttributeKey<Long> heartBeatAttr = AttributeKey.valueOf("HEARTBEAt_TIMES");
        ctx.channel().attr(heartBeatAttr).set(0L);
        // 在redis上记录每个user的channelId，15秒没有心跳，则自动过期 这个是redis的在线标识符
        String key = String.join(":", IMRedisKey.IM_ROOM_USER_ID, username,roomId);
        redisTemplate.opsForValue().set(key, IMServerGroup.serverId, IMConstant.ONLINE_TIMEOUT_SECOND, TimeUnit.SECONDS);
        // 响应ws
        IMSendInfo<Object> sendInfo = new IMSendInfo<>();
        sendInfo.setCmd(IMCmdType.TEAM_SUCCESS_MESSAGE.code());
        String message="用户："+username+"加入房间"+roomId+"成功";
        sendInfo.setData(message);
        ctx.channel().writeAndFlush(sendInfo);
    }
    @Override
    public RunTrackMessage transForm(Object o) {
        HashMap map = (HashMap) o;
        return BeanUtil.fillBeanWithMap(map, new RunTrackMessage(), false);
    }
}
